﻿using System;
using System.Data;
using System.Windows.Forms;
using MySqlConnector;

namespace Front._1124
{
    public partial class AddBookForm : Form
    {
        public AddBookForm()
        {
            InitializeComponent();
            InitControls(); // 初始化控件选项
        }

        // 初始化下拉框、列表框选项
        private void InitControls()
        {
            // 图书版本ListBox
            listBoxEdition.Items.AddRange(new string[] { "第一版", "第二版", "第三版", "第四版", "第五版" });
            
            // 出版社ComboBox
            publishId.Items.AddRange(new string[] { "人民邮电出版社", "机械工业出版社", "电子工业出版社" });
            
            // 图书分类ComboBox
            comboBoxCategory.Items.AddRange(new string[] { "计算机", "文学", "科技", "教育" });
            
            // 书架ComboBox
            comboBoxBookshelf.Items.AddRange(new string[] { "A区1架", "A区2架", "B区1架" });
            
            // 日期默认当前时间
            dateTimePickerPublish.Value = DateTime.Now;
            dateTimePickerPurchase.Value = DateTime.Now;
            
            // 图书简介多行文本框
            textBoxIntroduction.Multiline = true;
            textBoxIntroduction.ScrollBars = ScrollBars.Vertical;
            
            // 默认选中“在馆”单选框
            radioButtonInStock.Checked = true;
        }

        // 提交按钮点击事件（已绑定）
        // private void buttonSubmit_Click(object sender, EventArgs e)
        // {
        //     try
        //     {
        //         // 获取所有输入值（控件名和设计器一致）
        //         string bookId = isbn.Text.Trim();
        //         string bookName = bookname.Text.Trim();
        //         string publisher = this.publishId.Text;
        //         string author = this.author.Text.Trim();
        //         DateTime publishDate = dateTimePickerPublish.Value;
        //         decimal price = numericUpDownPrice.Value;
        //         string category = comboBoxCategory.Text;
        //         int totalPages = (int)numericUpDownPages.Value;
        //         string edition = listBoxEdition.SelectedItem?.ToString() ?? "";
        //         string introduction = textBoxIntroduction.Text.Trim();
        //         DateTime purchaseDate = dateTimePickerPurchase.Value;
        //         string status = radioButtonInStock.Checked ? "在馆" : radioButtonBorrowed.Checked ? "借出" : "损坏";
        //         string bookshelf = comboBoxBookshelf.Text;
        //
        //         // 验证必填项
        //         if (string.IsNullOrEmpty(bookId) || string.IsNullOrEmpty(bookName))
        //         {
        //             MessageBox.Show("书号和图书名称不能为空！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        //             return;
        //         }
        //
        //         // 提交成功提示
        //         MessageBox.Show(
        //             $"提交成功！\n\n书号：{bookId}\n名称：{bookName}\n出版社：{publisher}\n状态：{status}",
        //             "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
        //
        //         // 清空表单
        //         ClearForm();
        //     }
        //     catch (Exception ex)
        //     {
        //         MessageBox.Show($"提交失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        //     }
        // }

        // 清空表单
        private void ClearForm()
        {
            isbn.Clear();
            bookname.Clear();
            publishId.SelectedIndex = -1;
            author.Clear();
            dateTimePickerPublish.Value = DateTime.Now;
            numericUpDownPrice.Value = 0;
            comboBoxCategory.SelectedIndex = -1;
            numericUpDownPages.Value = 0;
            listBoxEdition.ClearSelected();
            textBoxIntroduction.Clear();
            dateTimePickerPurchase.Value = DateTime.Now;
            radioButtonInStock.Checked = true;
            comboBoxBookshelf.SelectedIndex = -1;
        }
        private void comboBoxPublisher_SelectedIndexChanged(object sender, EventArgs e)
        {
            // 这里写下拉框选项变化时的逻辑（比如联动其他控件）
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //执行数据保存
            using var connection = new MySqlConnection("server=localhost;port=3306;database=book;user=root;password=root;charset=utf8mb4;AllowPublicKeyRetrieval=True;");
            connection.Open();

            string sql =
                "insert  into `book_info`(`isbn`,`book_name`,`author`,`publisher_id`,`publish_date`,`book_category`,`book_price`,`book_pages`,`book_desc`,`book_status`,`shelf_id`,`purchase_date`,`book_version`,`create_time`) values \n(@isbn,@book_name,'刘增杰',@publisher_id,'2021-06-01','计算机科学',59.80,320,'讲解MySQL基础与实战开发',1,1,'2023-01-10','第2版','2025-10-10 10:11:29');";
            
            //创建command对象
            using var command = new MySqlCommand(sql, connection);
            //绑定参数
            command.Parameters.AddWithValue("isbn",this.isbn.Text);
            command.Parameters.AddWithValue("bookname",this.bookname.Text);
            command.Parameters.AddWithValue("author",this.author.Text);
            command.Parameters.AddWithValue("publishId",this.publishId.Text);
            
            
            
            //执行新增
            int count = command.ExecuteNonQuery();
            if (count > 0)
            {
                MessageBox.Show("新增成功");
                this.DialogResult = DialogResult.OK;
                //关闭新增窗口
                this.Close();
            }
            else
            {
                MessageBox.Show("新增失败");
            }

        }


        private void AddBookForm_Load(object sender, EventArgs e)
        {
            Init();
        }

        private void Init()
        {
            
        }

        private void GetAllPublishers()
        {
            using var connection = new MySqlConnection("server=localhost;port=3306;database=book;user=root;password=root;charset=utf8mb4;AllowPublicKeyRetrieval=True;");
            connection.Open();
        
            string sql = "select publisher_id,publisher_name from publisher_info";
            //创建适配器对象
            MySqlDataAdapter adapter = new MySqlDataAdapter(sql, connection);
            //创建数据库
            DataSet dataSet = new DataSet();
            //填充数据
            adapter.Fill(dataSet, "publisher_info");
            //绑定数据
            DataTable? dataTable = dataSet.Tables["publisher_info"];
            //插入全部行
            DataRow row = dataTable.NewRow();
            row[0] = "0";
            row[1] = "全部";
            dataTable.Rows.InsertAt(row,0);
            //绑定数据
            this.publishId.DataSource = dataTable;
            this.publishId.ValueMember = dataTable.Columns[0].ColumnName;
            this.publishId.DisplayMember = dataTable.Columns[1].ColumnName;
        }
        
        
    }
}